<template>
  <div class="wrapper" style="position: absolute; z-index: 200;top: 14px;width: auto">
    <div class="selectModelType" >
      <div class="tip"><p>功能面板 | 地图量测</p></div>
      <el-button type="primary" size="mini" plain @click="init('line')">距离</el-button>
      <el-button type="primary" size="mini" plain @click="init('polygon')">面积</el-button>
      <el-button type="danger" size="mini" plain @click="clearDrawingBoard()">清除</el-button>
    </div>
    <div id="toolTip" style="z-index: 1000;display:none;position:absolute;height:20px;width:160px;background:olive;top:0px;left:0px;font-size: 8px">
      <el-button id="toolTipButton" type="danger" size="mini" style="" plain @click="clearDrawingBoard()">清除</el-button>
    </div>
    <!--    <my-viewer :mapProps="mapProps" @viewerisok=""></my-viewer>-->
  </div>
</template>

<script>
  // import myViewer from "../cesiumViewer";
  // import {measureUtils} from "../../script/measureUtils"
  // import {gisStr,gisNum,funct1,funct2} from "../../script/test"
  export default {
    name: "measure",
    data(){
      return{
        handler:null,
        scene:null,
        drawingMode:'',
        tempPoints:[],
        tempEntities:[],
        activePoint:undefined,
        activeShape:undefined,
        floatingPoint:null,
        activeShapePoints:[],
        finalEntity:null,
      }
    },
    components:{
      // myViewer
    },
    mounted() {
      console.log("我又回来了 gisleung")
      this.scene = viewer.scene;
      mapBaseF.setContainer('none','none','none','none','none','','none','none')

      //双击鼠标左键清除默认事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      viewer.scene.globe.depthTestAgainstTerrain = true;//开启地形深度检测

    },
    methods:{
      init(drawingMode){
        this.drawingMode = drawingMode;
        let tooltipFlag = true;
        let tooltip = document.getElementById("toolTip");

        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
        //鼠标左键
        this.handler.setInputAction( (event) => {
          let earthPosition = viewer.scene.pickPosition(event.position);
          // let earthPosition = viewer.camera.pickEllipsoid(event.position, this.scene.globe.ellipsoid);
          //viewer.camera.pickEllipsoid(click.position, this.scene.globe.ellipsoid);

          if (Cesium.defined(earthPosition)) {
            if (this.activeShapePoints.length === 0) {
              this.floatingPoint = this.createPoint(earthPosition);
              this.activeShapePoints.push(earthPosition);
              let dynamicPositions = new Cesium.CallbackProperty(() => {
                if (this.drawingMode === 'polygon') {
                  return new Cesium.PolygonHierarchy(this.activeShapePoints);
                }
                return this.activeShapePoints; //是否更改了
              }, false);

              this.activeShape = this.drawShape(dynamicPositions);//绘制动态图
            }
            this.activeShapePoints.push(earthPosition);
            this.createPoint(earthPosition);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)



        //鼠标移动
        this.handler.setInputAction((event) => {
          this.setTooltip(tooltip,event,tooltipFlag)
          if (Cesium.defined(this.floatingPoint)) {
            let newPosition = viewer.scene.pickPosition(event.endPosition);
            if (Cesium.defined(newPosition)) {
              this.floatingPoint.position.setValue(newPosition);
              this.activeShapePoints.pop();
              this.activeShapePoints.push(newPosition);
            }
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        //鼠标右键
        this.handler.setInputAction( (event) => {
          if(tooltipFlag){
            if (this.drawingMode === 'polygon'){
              let theDis = this.getPolygonArea(this.activeShapePoints);
              //新增一个lable，计算面积
              viewer.entities.add({
                position: this.activeShapePoints[this.activeShapePoints.length-2],
                label: {
                  text: theDis + '',
                  font: '18px sans-serif',
                  fillColor: Cesium.Color.GOLD,
                  style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                  outlineWidth: 2,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  pixelOffset: new Cesium.Cartesian2(20, -20),
                  // heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                  // clampToGround: true,
                }
              });
            }
            tooltip.style.display = "none";
            tooltipFlag = false;
            this.terminateShape();
          }

        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      },
      //tooltip跟随
      setTooltip(tooltip,event,tooltipFlag){
        if(tooltipFlag){
          tooltip.style.left = event.endPosition.x +40+ "px";
          tooltip.style.top = event.endPosition.y+0+ "px";
          tooltip.innerHTML = '左键选择节点，右键完成量测';
          tooltip.style.display = "block";
        }else {

          tooltip.innerHTML = '22'
        }



      },


      createPoint(worldPosition) {
        let point;
        //需要判断当前是线 还是 面，如果是面的话 就不能加label
        if(this.drawingMode == 'line'){
          let textDisance = this.getSpaceDistance(this.activeShapePoints)
          point = viewer.entities.add({
            position: worldPosition,
            point: {
              pixelSize: 5,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
              // heightReference:Cesium.HeightReference.NONE
            },
            label: {
              text: textDisance,
              font: '18px sans-serif',
              fillColor: Cesium.Color.GOLD,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineWidth: 2,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(20, -20),
              // heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
              // clampToGround: true,
            }
          });
        }else if (this.drawingMode == 'polygon'){
          point = viewer.entities.add({
            position: worldPosition,
            point: {
              pixelSize: 5,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
              // heightReference:Cesium.HeightReference.NONE
            }
          });
        }

        return point;
      },

      //绘制图形。线和面
      drawShape(positionData) {
        let shape;
        if (this.drawingMode === 'line') {
          shape = viewer.entities.add({
            polyline: {
              positions: positionData,
              show: true,
              material: Cesium.Color.RED,
              width: 2,
              clampToGround: true,
            }
          });
        }else if (this.drawingMode === 'polygon') {
          shape = viewer.entities.add({
            polygon: {
              hierarchy: positionData,
              material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
            }
          });


        }
        return shape;
      },

      terminateShape() {
        this.activeShapePoints.pop();//去除最后一个动态点
        if(this.activeShapePoints.length){
          this.finalEntity = this.drawShape(this.activeShapePoints);//绘制最终图
        }
        viewer.entities.remove(this.floatingPoint);//去除动态点图形（当前鼠标点）
        viewer.entities.remove(this.activeShape);//去除动态图形
        this.floatingPoint = undefined;
        this.activeShape = undefined;
        this.activeShapePoints = [];

        if (this.handler != null) {
          this.handler.destroy();
        }


      },

      //计算距离
      getSpaceDistance(positions) {
        let distance = 0;
        for (let i = 0; i < positions.length - 1; i++) {

          let point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
          let point2cartographic = Cesium.Cartographic.fromCartesian(positions[i+1]);
          /**根据经纬度计算出距离**/
          let geodesic = new Cesium.EllipsoidGeodesic();
          geodesic.setEndPoints(point1cartographic, point2cartographic);
          let s = geodesic.surfaceDistance;
          //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
          //返回两点之间的距离
          s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
          distance = distance + s;
        }
        return distance.toFixed(2);
      },

      //计算面积
      getPolygonArea(point) {//输入应该是经纬度
        //把point转成经纬度
        let points = [];
        point.forEach((item,index) =>{
          let cartographic = Cesium.Cartographic.fromCartesian(item);
          let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
          let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
          points.push({ lon: longitudeString, lat: latitudeString });
        });

        let earthRadiusMeters = 6371000.0;
        let radiansPerDegree = Math.PI / 180.0;


        let totalAngle = 0;
        for (let i = 0; i < points.length; i++) {
          let j = (i + 1) % points.length;
          let k = (i + 2) % points.length;
          totalAngle += this.Angle(points[i], points[j], points[k]);
        }
        let planarTotalAngle = (points.length - 2) * 180.0;
        let sphericalExcess = totalAngle - planarTotalAngle;
        if (sphericalExcess > 420.0) {
          totalAngle = points.length * 360.0 - totalAngle;
          sphericalExcess = totalAngle - planarTotalAngle;
        } else if (sphericalExcess > 300.0 && sphericalExcess < 420.0) {
          sphericalExcess = Math.abs(360.0 - sphericalExcess);
        }
        return sphericalExcess * radiansPerDegree * earthRadiusMeters * earthRadiusMeters;
      },
      Angle(p1, p2, p3) {
        let bearing21 = this.Bearing(p2, p1);
        let bearing23 = this.Bearing(p2, p3);
        let angle = bearing21 - bearing23;
        if (angle < 0) {
          angle += 360;
        }
        return angle;
      },
      Bearing(from, to) {
        let degreesPerRadian = 180.0 / Math.PI;
        let radiansPerDegree = Math.PI / 180.0;
        let lat1 = from.lat * radiansPerDegree;
        let lon1 = from.lon * radiansPerDegree;
        let lat2 = to.lat * radiansPerDegree;
        let lon2 = to.lon * radiansPerDegree;
        let angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
        if (angle < 0) {
          angle += Math.PI * 2.0;
        }
        angle = angle * degreesPerRadian;
        return angle;
      },

      /**
       * 清除地图痕迹
       */
      clearDrawingBoard() {


        mapBaseF.removeAllNtt()
        this.tempEntities = [];

        this.handler=null;
        this.scene=null;
        this.drawingMode='';
        this.tempPoints=[];

        this.activePoint=undefined;
        this.activeShape=undefined;
        this.floatingPoint=null;
        this.activeShapePoints=[];
        this.finalEntity=null;

      },

    },
    destroyed() {
      // viewer.scene.mode = this.beginSceneMode
      mapBaseF.removeAllNtt()
    }
  }
</script>

<style scoped>

</style>
